const jwt = require('jsonwebtoken');

const JWT_SECRET = 'music_player_secret_key_2024';
const JWT_EXPIRES_IN = '7d';

// 生成token
function generateToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
}

// 验证token
function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
}

// 从请求头中提取token
function extractTokenFromHeader(authorization) {
  if (!authorization) return null;
  const parts = authorization.split(' ');
  if (parts.length === 2 && parts[0] === 'Bearer') {
    return parts[1];
  }
  return null;
}

module.exports = {
  generateToken,
  verifyToken,
  extractTokenFromHeader
};
